package cn.ad.service;

import cn.ad.common.DataUtils;
import cn.ad.exception.AdvertiserValidateException;
import cn.ad.handler.SqlSessionHandler;
import cn.ad.interceptor.PageParameter;
import cn.ad.model.*;
import cn.ad.entity.Advertiser;
import cn.ad.entity.AdvertiserInfo;
import cn.ad.entity.Platform;
import cn.ad.entity.Qualification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


/**
 * @author Administrator
 *
 */
@Service
public class AdvertiserService {


	private static Logger logger = LoggerFactory.getLogger(AdvertiserService.class);

	//GDT_ADX平台对应的channel值
	private static final Integer GDT_ADX_CHANNEL=3;
	
	//百度ADX平台对应的channel
	private static final Integer BAIDU_ADX_CHANNEL=3;

	@Autowired
	private SqlSessionHandler sqlSessionHandler;

	public ResultSetList<AdvertiserModel> findAdverties(String query, int offset, int limit, String sortby, String order, Integer agencyId, Integer advertiserId) {
		Map<String, Object> map = new HashMap<>(5);
		map.put("sortby", sortby);
		map.put("key", query);
		map.put("order", order);
		map.put("agencyId", agencyId);
		map.put("id", advertiserId);
		PageParameter page = new PageParameter(offset, limit);
		List<AdvertiserModel> advertiserlist = sqlSessionHandler.selectList("advertiserMapper.advertiser:list:page", map, page);
		ResultSetList<AdvertiserModel> list = new ResultSetList<AdvertiserModel>(page.getTotalCount(), advertiserlist);

		return list;
	}

	public ResultSetList<AdvertiserModel> findAdvertisers(Map<String, Object> searchMap) {
		Integer offset= Integer.parseInt(searchMap.get("offset").toString());
		Integer limit= Integer.parseInt(searchMap.get("limit").toString());
		PageParameter page=new PageParameter(offset,limit);
		List<AdvertiserModel> list = sqlSessionHandler.selectList("advertiserMapper.advertiser:list:page", searchMap, page);
		ResultSetList<AdvertiserModel> result = new ResultSetList<AdvertiserModel>(page.getTotalCount(), list);
		return result;
	}

	/**
	 * 新增广告主
	 */
	public void addAdvertiser(Advertiser advertiser){
		if(isRepeat(advertiser)){
			throw new AdvertiserValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_REPEAT);
		}
		sqlSessionHandler.insert("advertiserMapper.insert", advertiser);

		logger.info("添加了广告主{}",advertiser.getName());
		
	}

	@Transactional
	public Advertiser addAdvertisers(Advertiser advertiser) {
		if(isRepeat(advertiser)){
			throw new AdvertiserValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_REPEAT);
		}
		sqlSessionHandler.insert("advertiserMapper.insert", advertiser);
		logger.info("===========Falcon Advertiser 添加成功=======");
		List<Qualification> qualificationList = new ArrayList<Qualification>();
		//保存行业资质
		List<Qualification> optionQualifications = advertiser.getQualificationParam();
		
		if(optionQualifications != null && optionQualifications.size()>0){
			logger.info("添加其他资质证明");
			for(Qualification optionQualification : optionQualifications){
				optionQualification.setAdvertiserId(advertiser.getId());
				optionQualification.setType(1);
				optionQualification.setStatus(1);
				qualificationList.add(optionQualification);
			}
			sqlSessionHandler.insert("qualificationMapper.insert:list", qualificationList);
			logger.info("====添加其他资质证明成功===");
		}

		//查询出平台列表
		List<Platform> list = sqlSessionHandler.selectList("platformMapper.selectPlatformist", null);
		for (Platform platform:list){
			Map<String,Object> map=new HashMap<>();
			map.put("advertiserId",advertiser.getId());
			map.put("platformId",platform.getId());
			map.put("status",1);
			//判断当前平台是否需要提交审核
			if (advertiser.getIsAudit().equals(1)&& Arrays.asList(advertiser.getPlatforms()).contains(platform.getId())){
				if (platform.getChannel()!=GDT_ADX_CHANNEL && platform.getChannel()!=BAIDU_ADX_CHANNEL){
					//除广点通以外的广告主，因为不需要提交审核，直接置为2审核通过
					map.put("auditStatus",2);
				}else{
					map.put("auditStatus",1);
				}
			}else{
				//如果没有提交审核
				map.put("auditStatus",0);
			}

			sqlSessionHandler.insert("advertiserAuditMapper.insert",map);
		}
		logger.info("===========Advertiser 添加成功=========");
		return getAdvertiserById(advertiser.getId());
	}



	@Transactional
	public void advertiserAudit(Integer id) {
		getAdvertiserById(id);
		Map<String,Object> map=new HashMap<>();
		map.put("advertiserId",id);
		map.put("platformId",1);  //Falcon 猎鹰网络
		map.put("auditStatus",2); //默认审核通过
		map.put("status",1);
		Integer flag=sqlSessionHandler.selectOne("advertiserAuditMapper.check:isExists",map);
		if (flag>0){
			sqlSessionHandler.update("advertiserAuditMapper.update:hasExists",map);
		}else{
			sqlSessionHandler.insert("advertiserAuditMapper.insert",map);
		}
	}

	/**
	 * 根据id查询单个广告主
	 */
	public Advertiser getAdvertiserById(Integer id) {
		Advertiser advertiser=sqlSessionHandler.selectOne("advertiserMapper.selectById", id);
		if (advertiser==null){
			throw new AdvertiserValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_NOTFOUND);
		}
		Map<String,Object> map=new HashMap<>();
		map.put("advertiserId",advertiser.getId());
		map.put("type",1);
//		List<String> list=sqlSessionHandler.selectList("qualificationMapper.selectByAdId",map);
//		advertiser.setQualifications((String[]) list.toArray(new String[list.size()]));
		List<Qualification> qualificationList = sqlSessionHandler.selectList("qualificationMapper.select:list:By:AdId", map);
		advertiser.setQualificationParam(qualificationList);
		return advertiser;
	}

	public AdvertiserInfo getAdvertiser(Integer id) {
		return sqlSessionHandler.selectOne("advertiserMapper.selectOne", id);
	}

	/**
	 * 删除单个广告主，虚拟删除，实际为update
	 */
	public void deleteAdvertiser(Integer id) {
		 sqlSessionHandler.update("advertiserMapper.delete", id);
	}

	/**
	 * 更新广告主信息
	 */
	@Transactional
	public void edit(Advertiser advertiser){
		if( isRepeat(advertiser)){
			throw new AdvertiserValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_REPEAT);
		}
		
		sqlSessionHandler.update("advertiserMapper.update", advertiser);
		logger.info("编辑了广告主{}({})",advertiser.getName(),advertiser.getId());

		sqlSessionHandler.selectOne("qualificationMapper.delete",advertiser.getId());
		//编辑行业资质
		List<Qualification> optionQualifications = advertiser.getQualificationParam();
		List<Qualification> qualificationList = new ArrayList<Qualification>();
		//保存行业资质
		if(optionQualifications != null && optionQualifications.size()>0){
			for(Qualification optionQualification : optionQualifications){
				optionQualification.setAdvertiserId(advertiser.getId());
				optionQualification.setType(1);
				optionQualification.setStatus(1);
				qualificationList.add(optionQualification);
			}
			sqlSessionHandler.insert("qualificationMapper.insert:list", qualificationList);
		}

	}

	/**
	 * 更新广告主余额
	 *
	 * @param advertiser
	 */
	public boolean updateAdvertiserAmount(Advertiser advertiser, boolean isPlus) {

		if (null == advertiser || 0 == advertiser.getId()) {
			throw new AdvertiserValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_NOTFOUND);
		}
		AdvertiserInfo advertiserObj = this.getAdvertiser(advertiser.getId());
		if (null == advertiserObj) {
			throw new AdvertiserValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_NOTFOUND);
		}
		if (!isPlus) {
			if (BigDecimal.ZERO.compareTo(advertiserObj.getBalanceCash()) == 0) {
				throw new AdvertiserValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_AMOUNT);
			}
			if (!DataUtils.compare(advertiserObj.getBalanceCash(), advertiser.getBalanceCash())) {
				throw new AdvertiserValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_AMOUNT);
			} else {
				advertiserObj.setBalanceCash(DataUtils.sub(advertiserObj.getBalanceCash(), advertiser.getBalanceCash()));
			}
		} else {
			advertiserObj.setBalanceCash(DataUtils.add(advertiserObj.getBalanceCash(), advertiser.getBalanceCash()));
		}
		sqlSessionHandler.update("advertiserMapper.update", advertiserObj);
		return true;
	}

	public List<DropDownModel> getSelectList(Integer userId) {
		// TODO Auto-generated method stub
		return sqlSessionHandler.selectList("advertiserMapper.advertiser:drop:down:list", userId);
	}
	
	private boolean isRepeat(Advertiser advertiser){
		Integer count = sqlSessionHandler.selectOne("advertiserMapper.advertiser:checkname", advertiser);
		return count >0;
	}

	public List<AdvertiserAuditModel> getAuditStatus(Integer advertiserId, Integer status) {
		Map<String,Object> map=new HashMap<>();
		map.put("advertiserId",advertiserId);
		map.put("auditStatus",status);
		return sqlSessionHandler.selectList("advertiserAuditMapper.selectByAdIdAndStatus",map);
	}

	public List<AdvertiserPlatformAuditModel> getAuditStatus(Integer advertiserId) {
		this.getAdvertiserById(advertiserId);
		return sqlSessionHandler.selectList("advertiserAuditMapper.select:By:AdvertiserId",advertiserId);
	}

	/**
	 * 获取资质列表
	 * @param type
	 * @return
	 */
	public List<QualificationType> queryQualificationTypeList(int type){
		if(type == 1){
			return sqlSessionHandler.selectList("advertiserMapper.select:main:qualification:type", null);
		}else if(type == 2){
			return sqlSessionHandler.selectList("advertiserMapper.select:optional:qualification:type", null);
		}else{
			return null;
		}
	}

}
